package com.web.controller.web;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.web.dao.*;
import com.web.domain.WebResponse;
import com.web.domain.dataTable.BootstrapTableColumns;
import com.web.domain.dataTable.BootstrapTableResponse;
import com.web.entity.*;
import com.web.manager.FileUpLoadManager;
import com.web.manager.jpush.SendJPushMessage;
import com.xkk.utils.UUIDUtil;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;

import static com.web.manager.CoreManager.countTotalVal;

/**
 * @author FDjavaone
 * @date 2017/10/18
 */

@Controller
public class WebWithdrawController {
    @Autowired
    private WithdrawApplyMapper withdrawApplyMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private FileUpLoadManager fileUpLoadManager;
    @Autowired
    private CompanyBonusDetailMapper companyBonusDetailMapper;
    @Autowired
    private CompanyPoundageDetailMapper companyPoundageDetailMapper;
    @Autowired
    private ProfitDetailMapper profitDetailMapper;
    @Autowired
    private MerchantDetailMapper merchantDetailMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private CompanyReportMapper companyReportMapper;


    @RequestMapping(value = "sysf/withdraw",
            method = RequestMethod.GET)
    public String recharge(Model model, HttpServletRequest request) {
        return "withdrawApply";
    }

    @RequestMapping(value = "sysf/merchant",
            method = RequestMethod.GET)
    public String merchant(Model model, HttpServletRequest request) {
        return "merchantDetail";
    }

    @RequestMapping(value = "sysf/companyFundCount",
            method = RequestMethod.GET)
    public String companyFundCount(Model model, HttpServletRequest request) {
        return "companyFundCount";
    }


    @Data
    public static class WithdrawColumns extends BootstrapTableColumns {
        private String name;
        private String phone;
        private Integer type;
        private Integer status;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date begin_createTime;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date end_createTime;
    }

    @RequestMapping("sysf/getWithdrawApply")
    @ResponseBody
    public BootstrapTableResponse getWithdrawApply(WithdrawColumns withdrawColumns) {

        if (StringUtils.isNotBlank(withdrawColumns.getName())) {
            withdrawColumns.setName("%" + withdrawColumns.getName() + "%");
        }
        if (StringUtils.isNotBlank(withdrawColumns.getPhone())) {
            withdrawColumns.setPhone("%" + withdrawColumns.getPhone() + "%");
        }
        PageHelper.startPage(withdrawColumns.getPageNumber(), withdrawColumns.getPageSize());
        Page<WithdrawApply> page = withdrawApplyMapper.selectAllwithdraws(withdrawColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }

    @Autowired
    private StoreMapper storeMapper;

    @RequestMapping(value = "/sysf/withdrawApply/confirm")
    @ResponseBody
    public WebResponse confirm(WithdrawApply withdrawApply, MultipartFile file) {
        Date date = new Date();
        try {
            WithdrawApply apply = withdrawApplyMapper.selectByPrimaryKey(withdrawApply.getId());
            InputStream is = file.getInputStream();
            String str = fileUpLoadManager.upload(is, UUIDUtil.getUUID() + file.getOriginalFilename());
            withdrawApply.setAccount("http://" + str);
            withdrawApply.setStatus(1);
            withdrawApply.setModifyTime(date);
            withdrawApplyMapper.updateByPrimaryKeySelective(withdrawApply);
            Account account = accountMapper.selectByMid(apply.getmId());
            Member member = memberMapper.selectByPrimaryKey(account.getmId());
            Store store = storeMapper.selectByMid(member.getId());

            CompanyReport companyReport = new CompanyReport();

            companyReport.setCreateTime(date);
            companyReport.setModifyTime(date);

            // 用户的对应账户金额，已经在申请时就已经扣除，此时做一个确认消息提醒
            String content = "尊敬的用户您的";
            if (apply.getType() == 1) {
                companyReport.setReserve1("分润提现通过");
                content += "分润账户提现申请，申请提现" + apply.getAmt() + "元。手续费" + apply.getPoundage() + "元，已经确认打款。";
                //对应扣除奖金池的金额
                platformMapper.bonusPoolSubstract(apply.getAmt().add(apply.getPoundage()), 1L);
                CompanyBonusDetail companyBonusDetail = new CompanyBonusDetail();
                companyBonusDetail.setCreateTime(date);
                companyBonusDetail.setModifyTime(date);
                companyBonusDetail.setContent("用户" + apply.getName() + apply.getPhone() + "提现" + apply.getAmt() + "元,手续费：" + apply.getPoundage() + "，提现id：" + apply.getId());
                companyBonusDetail.setDetail("-" + apply.getAmt().add(apply.getPoundage()));
                companyBonusDetail.setBal(platformMapper.selectByPrimaryKey(1L).getBonusPool().toString());
                companyBonusDetail.setFromNum(String.valueOf(apply.getId()));
                companyBonusDetail.setDescription("用户" + apply.getName() + apply.getPhone() + "提现" + apply.getAmt() + "元,手续费：" + apply.getPoundage() + "，提现id：" + apply.getId());
                companyBonusDetail.setName(apply.getName());
                companyBonusDetail.setPhone(apply.getPhone());
                companyBonusDetailMapper.insertSelective(companyBonusDetail);

                //标记冻结记录已打款
                if(apply.getRecordId()!=0){
                    ProfitDetail profitDetail =profitDetailMapper.selectByPrimaryKey(apply.getRecordId());
                    profitDetail.setModifyTime(date);
                    profitDetail.setContent(profitDetail.getContent()+"(已打款)");
                    profitDetailMapper.updateByPrimaryKeySelective(profitDetail);
                }else{
                    //兼容老数据
                    //分润账户明细生成
                    ProfitDetail profitDetail = new ProfitDetail();
                    profitDetail.setaId(account.getId());
                    profitDetail.setDetail("-" + apply.getAmt().add(apply.getPoundage()) + "(含手续费" + apply.getPoundage() + ")");
                    profitDetail.setContent("提现申请已打款，扣除已提现金额，不影响账户余额");
                    profitDetail.setCreateTime(date);
                    profitDetail.setModifyTime(date);
                    profitDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getProfit().toString());
                    profitDetail.setFromNum("");
                    profitDetail.setName(member.getName());
                    profitDetail.setPhone(member.getPhone());
                    profitDetailMapper.insertSelective(profitDetail);
                }
            } else if (apply.getType() == 2) {
                content += "商户货款提现申请，申请提现" + apply.getAmt() + "元。手续费" + apply.getPoundage() + "元，已经确认打款。";
                companyReport.setReserve1("货款提现通过");

                //标记冻结记录已打款
                if(apply.getRecordId()!=0){
                    MerchantDetail merchantDetail =merchantDetailMapper.selectByPrimaryKey(apply.getRecordId());
                    merchantDetail.setModifyTime(date);
                    merchantDetail.setContent(merchantDetail.getContent()+"(已打款)");
                    merchantDetailMapper.updateByPrimaryKeySelective(merchantDetail);
                }else{
                    //兼容老数据
                    MerchantDetail merchantDetail = new MerchantDetail();
                    merchantDetail.setaId(account.getId());
                    merchantDetail.setDetail("-" + apply.getAmt().add(apply.getPoundage()) + "(含手续费" + apply.getPoundage() + ")");
                    merchantDetail.setContent("提现申请已打款，扣除已提现金额，不影响账户余额");
                    merchantDetail.setCreateTime(date);
                    merchantDetail.setModifyTime(date);
                    merchantDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getMerchantPayment().toString());
                    merchantDetail.setName(member.getName());
                    merchantDetail.setPhone(member.getPhone());
                    merchantDetail.setFromNum("");
                    if (store != null) {
                        merchantDetail.setStore(store.getMerchantName());
                        merchantDetail.setStoreId(store.getId());
                    }
                    merchantDetail.setType(3);
                    merchantDetail.setTotalBal(accountMapper.countMerchantNum().toString());
                    merchantDetailMapper.insertSelective(merchantDetail);
                }
            }

            //公司手续费池资金增加
            companyReport.setWithdrawPoundage("+" + apply.getPoundage() + "\n\r=" + platformMapper.selectByPrimaryKey(1L).getPoundagePool().add(apply.getPoundage()));
            companyReport.setTotal("+" + apply.getPoundage() + "\n\r=" + countTotalVal(companyReport));

            companyReportMapper.insertSelective(companyReport);

            platformMapper.poundagePoolAdd(apply.getPoundage(), 1L);
            CompanyPoundageDetail companyPoundageDetail = new CompanyPoundageDetail();
            companyPoundageDetail.setCreateTime(date);
            companyPoundageDetail.setModifyTime(date);
            companyPoundageDetail.setContent("用户" + apply.getName() + apply.getPhone() + "提现" + apply.getAmt() + "元，手续费：" + apply.getPoundage() + "元，提现id：" + apply.getId());
            companyPoundageDetail.setDetail("+" + apply.getPoundage());
            companyPoundageDetail.setBal(platformMapper.selectByPrimaryKey(1L).getPoundagePool().toString());
            companyPoundageDetail.setFromNum(String.valueOf(apply.getId()));
            companyPoundageDetail.setDescription("用户" + apply.getName() + apply.getPhone() + "提现" + apply.getAmt() + "元，手续费：" + apply.getPoundage() + "元，提现id：" + apply.getId());
            companyPoundageDetail.setName(apply.getName());
            companyPoundageDetail.setPhone(apply.getPhone());
            companyPoundageDetailMapper.insertSelective(companyPoundageDetail);

            Message message = new Message();
            message.setModifyTime(date);
            message.setCreateTime(date);
            message.setContent(content);
            message.setTitle("提现结果");
            message.setFrom(0L);
            message.setFromName("系统");
            message.setTarget(apply.getmId());
            message.setTargetName("");
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);

            return WebResponse.ok("确认打款成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.fail(WebResponse.CF);
        }
    }


    @RequestMapping(value = "/sysf/withdrawApply/refuse")
    @ResponseBody
    public WebResponse refuse(WithdrawApply withdrawApply) {
        Date date = new Date();
        try {
            WithdrawApply apply = withdrawApplyMapper.selectByPrimaryKey(withdrawApply.getId());
            Account account = accountMapper.selectByMid(apply.getmId());
            Member member = memberMapper.selectByPrimaryKey(account.getmId());
            Store store = storeMapper.selectByMid(member.getId());
            // 审核拒绝归还对应账户冻结金额
            String content = "尊敬的用户您的";

            CompanyReport companyReport = new CompanyReport();

            companyReport.setCreateTime(date);
            companyReport.setModifyTime(date);
            companyReport.setAdd(apply.getAmt().toString());
            if (apply.getType() == 1) {
                companyReport.setReserve1("分润提现拒绝");

                BigDecimal profitRecord = new BigDecimal("0");

                companyReport.setProfitBal("+" + apply.getPoundage().add(apply.getAmt()));
                profitRecord = new BigDecimal(companyReport.getProfitBal());
                companyReport.setProfitBal((companyReport.getProfitBal() != null ? companyReport.getProfitBal() : "") + "\r\n=" + accountMapper.countProfitNum().add(profitRecord));
                companyReport.setTotal(profitRecord.toString() + "\n\r=" + countTotalVal(companyReport));


                //分润账户余额先冻结 提现金额和手续费
                account.setProfit(account.getProfit().add(apply.getAmt()).add(apply.getPoundage()));
                accountMapper.updateByPrimaryKeySelective(account);
                //分润账户明细生成
                ProfitDetail profitDetail = new ProfitDetail();
                profitDetail.setaId(account.getId());
                profitDetail.setDetail("+" + apply.getAmt().add(apply.getPoundage()) + "(含手续费" + apply.getPoundage() + ")");
                profitDetail.setContent("提现申请驳回归还审核中金额");
                profitDetail.setCreateTime(date);
                profitDetail.setModifyTime(date);
                profitDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getProfit().toString());
                profitDetail.setFromNum("");
                profitDetail.setName(member.getName());
                profitDetail.setPhone(member.getPhone());
                profitDetailMapper.insertSelective(profitDetail);


                content += "分润账户提现申请，申请提现" + apply.getAmt() + "元。手续费" + apply.getPoundage() + "元，提现申请被拒绝，原因：" + withdrawApply.getReason() + "审核中钱款已经归还到分润账户。";
            } else if (apply.getType() == 2) {
                companyReport.setReserve1("货款提现拒绝");

                BigDecimal profitRecord = new BigDecimal("0");

                companyReport.setUnWithdraw("+" + apply.getPoundage().add(apply.getAmt()));
                profitRecord = new BigDecimal(companyReport.getUnWithdraw());
                companyReport.setUnWithdraw((companyReport.getUnWithdraw() != null ? companyReport.getUnWithdraw() : "") + "\r\n=" + accountMapper.countMerchantNum().add(profitRecord));
                companyReport.setTotal(profitRecord.toString() + "\n\r=" + countTotalVal(companyReport));


                account.setMerchantPayment(account.getMerchantPayment().add(apply.getAmt()).add(apply.getPoundage()));
                accountMapper.updateByPrimaryKeySelective(account);

                MerchantDetail merchantDetail = new MerchantDetail();
                merchantDetail.setaId(account.getId());
                merchantDetail.setDetail("+" + apply.getAmt().add(apply.getPoundage()) + "(含手续费" + apply.getPoundage() + ")");
                merchantDetail.setContent("提现申请驳回归还审核中金额");
                merchantDetail.setCreateTime(date);
                merchantDetail.setModifyTime(date);
                merchantDetail.setBal(accountMapper.selectByPrimaryKey(account.getId()).getMerchantPayment().toString());
                merchantDetail.setName(member.getName());
                merchantDetail.setPhone(member.getPhone());
                merchantDetail.setFromNum("");
                if (store != null) {
                    merchantDetail.setStore(store.getMerchantName());
                    merchantDetail.setStoreId(store.getId());
                }
                merchantDetail.setType(3);
                merchantDetail.setTotalBal(accountMapper.countMerchantNum().toString());
                merchantDetailMapper.insertSelective(merchantDetail);

                content += "商户货款提现申请，申请提现" + apply.getAmt() + "元。手续费" + apply.getPoundage() + "元，提现申请被拒绝，原因：" + withdrawApply.getReason() + "审核中钱款已经归还到商户货款账户。";
            }

            companyReportMapper.insertSelective(companyReport);
            withdrawApply.setStatus(2);
            withdrawApply.setModifyTime(date);
            withdrawApplyMapper.updateByPrimaryKeySelective(withdrawApply);
            Message message = new Message();
            message.setModifyTime(date);
            message.setCreateTime(date);
            message.setContent(content);
            message.setTitle("提现结果");
            message.setFrom(0L);
            message.setFromName("系统");
            message.setTarget(apply.getmId());
            message.setTargetName("");
            messageMapper.insertSelective(message);
            SendJPushMessage.jPushByMessage(message);


            return WebResponse.ok("操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.fail(WebResponse.CF);
        }
    }


    @RequestMapping("sysf/getCompanyFundCount")
    @ResponseBody
    public BootstrapTableResponse getCompanyFundCount(WithdrawColumns withdrawColumns) {

        PageHelper.startPage(withdrawColumns.getPageNumber(), withdrawColumns.getPageSize());
        Page<CompanyReport> page = companyReportMapper.selectByPage(withdrawColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }
}
